package cn.stylefeng.guns.sys.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.text.StringEscapeUtils;
//import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;


import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录工具类
 */
public class LogUtil {


    /**
     * 获取token和company_id
     *
     * @return
     */
    public static Map<String, String> tokenGetter() {
        Map<String, String> map1 = new HashMap<>();
        // 请求地址（测试）
//        String url = "http://supply.metacatering.cn/api/chain/login/account";
        // 请求地址（正式）
        String url = "https://supply.imugua.tech/api/chain/login/account";
        // post请求
        HttpClient httpClient = null;
        HttpPost postMethod = null;
        HttpResponse response = null;
        String responseContent = null;
        try {
            // 获取http客户端
            httpClient = HttpClients.createDefault();
            postMethod = new HttpPost(url);
            // 自定义对象
            Map<String, String> map = new HashMap<>();
            map.put("company_id", "10001");
//            map.put("userName", "songyue");//测试

            map.put("userName", "OA");//正式

            String password = "123456";
            for (int i = 0; i <= 2; i++) {
                // 此 MessageDigest 类为应用程序提供信息摘要算法的功能
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                // 转换为MD5码
                byte[] digest = md5.digest(password.getBytes("utf-8"));
                password = ByteUtils.toHexString(digest);
            }
//            map.put("password","c56d0e9a7ccec67b4ea131655038d604");
            map.put("password", password);

            // 设置请求头
            postMethod.addHeader("Content-Type", "application/json;charset=utf8");
            // 封装请求体
            postMethod.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
            // 发送请求
            response = httpClient.execute(postMethod);
            // 获取响应结果
            //int statusCode = response.getStatusLine().getStatusCode();
            //System.out.println("响应结果"+statusCode);
            // 响应对象
            HttpEntity httpEntity = response.getEntity();
            //System.out.println("响应对象"+httpEntity);
            // 响应的字符串
            responseContent = EntityUtils.toString(httpEntity, "UTF-8");
            //System.out.println("响应字符串"+responseContent);
            //转化为JSON格式
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            String companyId = jsonObject.getString("company_id");
            String token = jsonObject.getString("session_id");
            String SHOP_ID = jsonObject.getString("shop_id");
            map1.put("companyId", companyId);
            map1.put("token", token);
            map1.put("SHOP_ID", SHOP_ID);
            //System.out.println("company_id"+companyId);
            //System.out.println("sessionId"+token);
            //释放资源
            EntityUtils.consume(httpEntity);
            return map1;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 携带token获取门店数据
     */
    public static List<Map<String, String>> getStore() {
        List<Map<String, String>> list = new ArrayList<>();
        // 请求地址（测试）
//        String url = "http://supply.metacatering.cn/api/chain/relation/queryStore";
        //请求地址（正式）
        String url = "https://supply.imugua.tech/api/chain/relation/queryStore";
        // post请求
        HttpClient httpClient = null;
        HttpPost postMethod = null;
        HttpResponse response = null;
        String responseContent = null;
        PrintWriter out = null;
        try {
            // 获取http客户端
            httpClient = HttpClients.createDefault();
            postMethod = new HttpPost(url);
            // 自定义对象
            Map<String, String> map = new HashMap<>();
            //map.put("token",tokenGetter().get("token"));
            map.put("COMPANY_ID", tokenGetter().get("companyId"));
            // 设置请求头
            postMethod.addHeader("Content-Type", "application/json;charset=utf8");
            postMethod.setHeader("token", tokenGetter().get("token"));
            // 封装请求体
            postMethod.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
            // 发送请求
            response = httpClient.execute(postMethod);
            // 获取响应结果
            int statusCode = response.getStatusLine().getStatusCode();
            //System.out.println("响应结果"+statusCode);
            // 响应对象
            HttpEntity httpEntity = response.getEntity();
            //System.out.println("响应对象"+httpEntity);
            // 响应的字符串
            responseContent = EntityUtils.toString(httpEntity, "UTF-8");
            //System.out.println("响应字符串"+responseContent);
            //转化为JSON格式
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            int code = Integer.parseInt(jsonObject.getString("code"));
            if (code == 0) {
                String data = jsonObject.getString("data");
                //将json格式的数据转换成list
                List<String> list1 = JSON.parseArray(StringEscapeUtils.unescapeHtml4(data), String.class);
                //将数据循环添加到list集合中
                for (int i = 0; i < list1.size(); i++) {
                    Map<String, String> map2 = new HashMap<>();
                    String[] split = list1.get(i).split(",");
                    //木瓜门店编号
                    map2.put("scmCode", split[3].replace("\"", ""));
                    //天财门店编号
                    map2.put("shopCode", split[4].replace("\"", ""));
                    //木瓜店名
                    map2.put("scmName", split[2].replace("\"", ""));
                    //天财店名
                    map2.put("shopName", split[9].replace("\"", ""));
                    //店名类型
                    map2.put("externalType", split[0].replace("[", ""));
                    //System.out.println("externalType=======---"+split[0].replace("[",""));
                    list.add(map2);
                }
                //String[] split = list1.get(0).split(",");
                //System.out.println("++++++====="+split);
                //System.out.println("++++++=====shuju"+split[3]);
                //System.out.println("+++6+666+6+66+"+list2.get(0));
                //StringUtils.substringBetween("{", "}");
                //释放资源
            } else {
                NullPointerException e=new NullPointerException();
                System.out.println("数据获取失败"+e.toString());

            }
                EntityUtils.consume(httpEntity);
                return list;


        } catch (Exception e) {
            return null;
        }

    }
}









